@extends('layouts.app')

@section('title', $title . '')

@section('main-content')
{{--    <div class="header">--}}
{{--        <div class="greeting" id="greeting">早上好！</div>--}}
{{--        <div class="date" id="current-date">{{ date('Y年m月d日 星期') . ['日', '一', '二', '三', '四', '五', '六'][date('w')] }}</div>--}}
{{--    </div>--}}

    <div class="balance-card">
        <div class="balance-label">本月结余</div>
        <div class="balance-amount">¥{{ number_format($currentBalance, 2) }}</div>
        <div class="balance-stats">
            <div class="stat">
                <div class="stat-label">本月收入</div>
                <div class="stat-value">¥{{ number_format($monthlyIncome, 2) }}</div>
            </div>
            <div class="stat">
                <div class="stat-label">本月支出</div>
                <div class="stat-value">¥{{ number_format($monthlyExpense, 2) }}</div>
            </div>
        </div>
    </div>

    <div class="quick-actions">
        <div class="section-title">快速记账</div>
        <div class="action-buttons">
            <button class="action-btn" onclick="window.location.href='{{ route('transaction.create', ['type' => 'expense']) }}'">
                <div class="action-icon expense-icon">-</div>
                <div class="action-text">记支出</div>
            </button>
            <button class="action-btn" onclick="window.location.href='{{ route('transaction.create', ['type' => 'income']) }}'">
                <div class="action-icon income-icon">+</div>
                <div class="action-text">记收入</div>
            </button>
        </div>
    </div>

    <div class="recent-transactions">
        <div class="section-title">最近交易</div>

        @if($recentTransactions->count() > 0)
            @foreach($recentTransactions as $transaction)
            <div class="transaction-item">
                <div class="item-user-avatar">
                    @if(isset($transaction['user_avatar_url']) && $transaction['user_avatar_url'])
                        <img src="{{ $transaction['user_avatar_url'] }}" alt="{{ $transaction['user_nickname'] ?? $transaction['user_name'] }}" style="width: 32px; height: 32px; border-radius: 50%; object-fit: cover;">
                    @else
                        {{ strtoupper(substr($transaction['user_nickname'] ?? $transaction['user_name'] ?? 'U', 0, 1)) }}
                    @endif
                </div>
                <div class="transaction-icon">{{ $transaction['icon'] }}</div>
                <div class="transaction-info">
                    <h4>{{ $transaction['category'] }}@if($transaction['sub_category'])·{{ $transaction['sub_category'] }}@endif</h4>
                    @if($transaction['description'])
                        <p class="transaction-desc">{{ $transaction['description'] }}</p>
                    @endif
                </div>
                <div class="transaction-amount {{ $transaction['type'] === 'income' ? 'income-amount' : 'expense-amount' }}">
                    {{ $transaction['type'] === 'income' ? '+' : '-' }}¥{{ number_format($transaction['amount'], 2) }}
                </div>
                <div class="transaction-options">
                    <button class="transaction-options-btn" onclick="toggleOptionsMenu({{ $transaction['id'] }})">
                        ⋯
                    </button>
                    <div class="transaction-options-menu" id="options-menu-{{ $transaction['id'] }}">
                        <button class="transaction-options-menu-item" onclick="viewTransaction({{ $transaction['id'] }})">
                            查看
                        </button>
                        <button class="transaction-options-menu-item" onclick="editTransaction({{ $transaction['id'] }})">
                            编辑
                        </button>
                        <button class="transaction-options-menu-item delete" onclick="deleteTransaction({{ $transaction['id'] }})">
                            删除
                        </button>
                    </div>
                </div>
            </div>
            @endforeach
        @else
            <div class="empty-state">
                <div class="empty-icon">📝</div>
                <div class="empty-text">暂无交易记录</div>
                <div class="empty-hint">点击上方按钮开始记账吧</div>
            </div>
        @endif
    </div>

    <!-- 删除确认模态框 -->
    <div class="modal" id="delete-transaction-modal" style="display: none;">
        <div class="modal-content" style="max-width: 400px;">
            <div class="modal-header">
                <h3>确认删除</h3>
                <button class="modal-close" id="delete-modal-close">&times;</button>
            </div>
            <div class="modal-body">
                <p style="text-align: center; margin: 20px 0;">确定要删除这条记账记录吗？</p>
                <p style="text-align: center; color: #999; font-size: 14px;">此操作不可撤销</p>
                <input type="hidden" id="delete-transaction-id">
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" id="delete-cancel-btn">取消</button>
                <button class="btn btn-danger" id="delete-confirm-btn">删除</button>
            </div>
        </div>
    </div>
@endsection

@push('styles')
<style>
/* 首页特有样式 - 基于原始styles.css */
.header {
    background: rgba(255,255,255,0.95);
    backdrop-filter: blur(20px);
    padding: 20px;
    text-align: center;
    border-bottom: 1px solid rgba(0,0,0,0.05);
}

.greeting {
    font-size: 24px;
    font-weight: 700;
    color: #2d3748;
    margin-bottom: 8px;
}

.date {
    color: #718096;
    font-size: 14px;
}

/* 余额卡片 */
.balance-card {
    margin: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 20px;
    padding: 30px 20px;
    color: white;
    box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
}

.balance-label {
    font-size: 14px;
    opacity: 0.8;
    margin-bottom: 8px;
}

.balance-amount {
    font-size: 36px;
    font-weight: 700;
    margin-bottom: 20px;
}

.balance-stats {
    display: flex;
    justify-content: space-between;
}

.stat {
    text-align: center;
}

.stat-label {
    font-size: 12px;
    opacity: 0.7;
    margin-bottom: 4px;
}

.stat-value {
    font-size: 16px;
    font-weight: 600;
}

/* 快速操作 */
.quick-actions {
    padding: 0 20px;
    margin-bottom: 20px;
}

.section-title {
    font-size: 18px;
    font-weight: 600;
    color: #2d3748;
    margin-bottom: 15px;
}

.action-buttons {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;
}

.action-btn {
    background: white;
    border: none;
    border-radius: 16px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 12px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    cursor: pointer;
    transition: all 0.3s ease;
}

.action-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 30px rgba(0,0,0,0.12);
}

.action-icon {
    width: 40px;
    height: 40px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
}

.expense-icon {
    background: linear-gradient(135deg, #ff6b6b, #ee5a24);
    color: white;
}

.income-icon {
    background: linear-gradient(135deg, #51cf66, #40c057);
    color: white;
}

.action-text {
    font-size: 16px;
    font-weight: 600;
    color: #2d3748;
}

/* 最近交易 */
.recent-transactions {
    padding: 0 20px;
}

.transaction-item {
    background: white;
    border-radius: 16px;
    padding: 16px;
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    gap: 0;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    transition: all 0.3s ease;
}

.transaction-item:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 20px rgba(0,0,0,0.1);
}

.item-user-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: 600;
    flex-shrink: 0;
}

.transaction-info {
    flex: 1;
    min-width: 0;
}

.transaction-info h4 {
    font-size: 15px;
    font-weight: 600;
    color: #2d3748;
    margin: 0 0 2px 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.transaction-desc {
    font-size: 12px;
    color: #718096;
    margin: 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.transaction-amount {
    font-size: 16px;
    font-weight: 700;
    margin-right: 8px;
    flex-shrink: 0;
}

.expense-amount {
    color: #e53e3e;
}

.income-amount {
    color: #38a169;
}
/* 操作按钮悬停效果 */
.transaction-options-menu {
    position: absolute;
    top: 100%;
    right: 0;
    background: white;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    z-index: 1000;
    min-width: 100px;
    width: 100px;
    overflow: hidden;
    display: none;
}

.transaction-options-menu.show {
    display: block;
}

.transaction-options-menu-item {
    padding: 10px 15px;
    cursor: pointer;
    font-size: 14px;
    color: #4a5568;
    transition: background-color 0.2s;
    border: none;
    background: none;
    width: 100%;
    text-align: left;
}

.transaction-options-menu-item:hover {
    background: #f8f9fa;
}

.transaction-options-menu-item.delete {
    color: #dc3545;
}

.transaction-options-menu-item.delete:hover {
    background: #fff5f5;
}

.transaction-options-btn {
    background: none;
    border: none;
    color: #999;
    font-size: 16px;
    cursor: pointer;
    padding: 8px;
    border-radius: 50%;
    transition: all 0.3s ease;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.transaction-options-btn:hover {
    background: #f8f9fa;
    color: #666;
}

/* 空状态 */
.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #718096;
}

.empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
    opacity: 0.5;
}

.empty-text {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 8px;
}

.empty-hint {
    font-size: 14px;
    opacity: 0.7;
}

/* 响应式设计 */
@media (max-width: 480px) {
    .balance-card {
        margin: 15px;
        padding: 25px 15px;
    }

    .balance-amount {
        font-size: 32px;
    }

    .quick-actions {
        padding: 0 15px;
    }

    .recent-transactions {
        padding: 0 15px;
    }

    .action-btn {
        padding: 16px;
        gap: 8px;
    }

    .action-icon {
        width: 36px;
        height: 36px;
        font-size: 18px;
    }

    .action-text {
        font-size: 14px;
    }

    .transaction-item {
        padding: 12px;
        gap: 0;
    }

    .transaction-info h4 {
        font-size: 14px;
    }

    .transaction-amount {
        font-size: 14px;
    }
}
</style>
@endpush

@push('scripts')
<script>
$(document).ready(function() {
    // 更新问候语
    // function updateGreeting() {
    //     const now = new Date();
    //     const hours = now.getHours();
    //     const greeting = $('#greeting');
    //
    //     if (hours >= 5 && hours < 12) {
    //         greeting.text('早上好！');
    //     } else if (hours >= 12 && hours < 18) {
    //         greeting.text('下午好！');
    //     } else {
    //         greeting.text('晚上好！');
    //     }
    // }

    // 初始化问候语
    // updateGreeting();

    // 每分钟更新一次问候语
    // setInterval(updateGreeting, 60000);

    // 切换操作菜单显示/隐藏
    window.toggleOptionsMenu = function(transactionId) {
        const menu = document.getElementById(`options-menu-${transactionId}`);
        const allMenus = document.querySelectorAll('.transaction-options-menu');

        // 隐藏其他菜单
        allMenus.forEach(m => {
            if (m.id !== `options-menu-${transactionId}`) {
                m.classList.remove('show');
            }
        });

        // 切换当前菜单
        menu.classList.toggle('show');
    };

    // 点击其他地方隐藏菜单
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.transaction-options').length) {
            $('.transaction-options-menu').removeClass('show');
        }
    });

    // 显示交易操作菜单
    window.editTransaction = function(transactionId) {
        // 隐藏操作菜单
        $(`#options-menu-${transactionId}`).removeClass('show');

        // 跳转到编辑页面
        window.location.href = `/transaction/${transactionId}/edit`;
    };

    // 查看交易记录
    window.viewTransaction = function(transactionId) {
        // 隐藏操作菜单
        $(`#options-menu-${transactionId}`).removeClass('show');

        // 跳转到查看页面
        window.location.href = `/transaction/${transactionId}`;
    };

    // 删除交易记录
    window.deleteTransaction = function(transactionId) {
        // 隐藏操作菜单
        $(`#options-menu-${transactionId}`).removeClass('show');

        // 显示删除确认模态框
        $('#delete-transaction-id').val(transactionId);
        $('#delete-transaction-modal').show();
    };

    // 确认删除交易记录
    $('#delete-confirm-btn').click(function() {
        const transactionId = $('#delete-transaction-id').val();

        $.ajax({
            url: `/transaction/${transactionId}`,
            method: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    showSuccess('交易记录删除成功');
                    $('#delete-transaction-modal').hide();
                    window.location.reload(); // 重新加载数据
                } else {
                    showError('删除失败：' + response.message);
                }
            },
            error: function(xhr) {
                showError('删除失败，请重试');
            }
        });
    });

    // 关闭模态框事件
    $('#edit-modal-close, #edit-cancel-btn').click(function() {
        $('#edit-transaction-modal').hide();
    });

    $('#delete-modal-close, #delete-cancel-btn').click(function() {
        $('#delete-transaction-modal').hide();
    });

    // 点击模态框背景关闭
    $('.modal').click(function(e) {
        if (e.target === this) {
            $(this).hide();
        }
    });

    // 定期刷新统计数据（每5分钟）
    setInterval(function() {
        refreshStats();
    }, 5 * 60 * 1000);

    // 刷新统计数据
    function refreshStats() {
        $.ajax({
            url: '{{ route("home.stats") ?? "#" }}',
            method: 'GET',
            success: function(response) {
                if (response.success) {
                    const data = response.data;

                    // 更新页面上的统计数据
                    $('.stat-value').eq(0).text('¥' + parseFloat(data.monthly_income).toLocaleString('zh-CN', {minimumFractionDigits: 2}));
                    $('.stat-value').eq(1).text('¥' + parseFloat(data.monthly_expense).toLocaleString('zh-CN', {minimumFractionDigits: 2}));
                }
            },
            error: function() {
                console.log('刷新统计数据失败');
            }
        });
    }
});
</script>
@endpush
